package com.xiaojie.controller;

import com.xiaojie.entity.Goods;
import com.xiaojie.lock.RedisLock;
import com.xiaojie.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaojie
 * @version 1.0
 * @description: 秒杀的接口
 * @date 2022/6/9 22:55
 */
@RestController
public class SeckillController {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private RedisLock redisLock;



    @GetMapping("/secKill")
    public String secKill(Long id) {
        try {
            if (!redisLock.tryLock()) {
                //获取锁失败
                return "活动太火了，请稍后重试";
            }
            Goods goods = goodsMapper.selectById(id);
            if (null == goods) {
                return "该商品没有秒杀活动";
            }
            if (goods.getStock() <= 0) {
                return "商品库存为空了。。。。。";
            }
            //减库存
            Integer result = goodsMapper.deceGoods(id);
            return result > 0 ? "秒杀成功" : "秒杀失败";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            redisLock.releaseLock();
        }
        return "fail";
    }
}
